package com.abaaba.project2.service.serviceImpl;

import com.abaaba.project2.bean.User;
import com.abaaba.project2.bean.UserExample;
import com.abaaba.project2.bean.bo.WxLoginBo;
import com.abaaba.project2.bean.bo.WxRegisterBo;
import com.abaaba.project2.bean.bo.wx.WxResetBo;
import com.abaaba.project2.bean.vo.UserLoginVo;
import com.abaaba.project2.mapper.UserMapper;
import com.abaaba.project2.mapper.VerifyCodeMapper;
import com.abaaba.project2.service.WxAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.lang.System;
import java.util.List;

@Service
public class WxAuthServiceImpl implements WxAuthService {
    @Autowired
    VerifyCodeMapper verifyCodeMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public UserLoginVo wxLogin(WxLoginBo wxLoginBo) {

        return null;
    }

    @Override
    public void insertVerifyCode(String mobile, String authcode) {
        if (verifyCodeMapper.selectCodeByMobile(mobile) != null) {
            verifyCodeMapper.updateCode(mobile, authcode);
        } else {
            verifyCodeMapper.insertCode(mobile, authcode);
        }
    }

    @Override
    public String selectCodeByMobile(String mobile) {
        return verifyCodeMapper.selectCodeByMobile(mobile);
    }

    @Override
    public void insertUser(WxRegisterBo wxRegisterBo) {
        User user = new User();
        user.setUsername(wxRegisterBo.getUsername());
        user.setPassword(wxRegisterBo.getPassword());
        user.setWeixinOpenid(wxRegisterBo.getWxCode());
        user.setMobile(wxRegisterBo.getMobile());
        user.setAddTime(new Date(System.currentTimeMillis()));
        user.setUpdateTime(user.getAddTime());
        userMapper.insertSelective(user);
    }

    @Override
    public String verifyUsername(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() != 0) {
            return users.get(0).getUsername();
        }
        return null;
    }

    @Override
    public void updateUser(User user, WxResetBo wxResetBo) {
        user.setPassword(wxResetBo.getPassword());
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User selectUserByMobile(String mobile) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andMobileEqualTo(mobile);
        criteria.andDeletedEqualTo(false);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 1) {
            return users.get(0);
        }
        return null;
    }
}
